package cn.org.donald.framework.controller;

import cn.org.donald.framework.handler.ServiceException;
import cn.org.donald.framework.pojo.vo.HttpResult;
import cn.org.donald.framework.service.CodeBuilderService;
import cn.org.donald.framework.service.SysTableService;
import cn.org.donald.framework.base.BaseController;
import cn.org.donald.framework.pojo.dto.CodeBuilder;
import cn.org.donald.framework.pojo.entity.Table;
import cn.org.donald.framework.util.ListUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * @author ： Donald
 * @date ： 2020/10/24 16:02
 * @description： 代码生成控制器
 */
@RestController
@RequestMapping("/admin")
@Api(value = "超级管理功能",description = "代码开发相关功能")
@RequiresRoles("admin")
public class CodeBuilderController extends BaseController {


    @Reference(version = "1.0.0",group = "donald")
    private SysTableService sysTableService;

    @Reference(version = "1.0.0",group = "donald")
    private CodeBuilderService codeBuilderService;


    @PostMapping("/codeBuilder")
    @ApiOperation(value = "代码生成接口")
    @ApiImplicitParam(name = "CodeBuilder",value = "代码生成设置参数",dataType = "CodeBuilder")
    public HttpResult getCode(@Validated @RequestBody CodeBuilder codeBuilder, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            throw new ServiceException(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        String tableName = codeBuilder.getTableName();
        if (sysTableService.isExistByTableName(tableName)){
            return codeBuilderService.build(codeBuilder) ? toResultSuccess("代码构建成功") : toResultFail("代码构建失败");
        }
        return toResultFail("数据库不存在");
    }


}
